package com.liukaixin.product.ru.business.team.jointeamapply;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.user.editUser.EditUserActivity;
import com.liukaixin.product.ru.data.model.Apply;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.ResultTypeEnum;
import com.liukaixin.product.ru.util.BusinessException;
import com.liukaixin.product.ru.util.CheckUtil;
import com.liukaixin.product.ru.util.LVCircularSmile;
import com.orhanobut.logger.Logger;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by liukaixin on 16/9/19.
 */
public class JoinTeamApplyAbilityFragment extends Fragment implements JoinTeamApplyContract.View {

    private JoinTeamApplyContract.Presenter presenter;

    @NonNull
    private static final String ARGUMENT_TEAM_ID = "TEAM_ID";
    @NonNull
    private static final String ARGUMENT_CREATOR_ID = "CREATOR_ID";

    @NonNull
    private static final String ARGUMENT_TEAM_NAME = "TEAM_NAME";
    @NonNull
    private static final String ARGUMENT_COMPETITION_NAME = "COMPETITION_NAME";

    private EditText abilityEdit;

    private LVCircularSmile loadingSmile;

    public JoinTeamApplyAbilityFragment() {
        // Requires empty public constructor
    }

    public static JoinTeamApplyAbilityFragment newInstance(
            Integer teamId, Integer creatorId,
            String teamName, String competitionName) {
        Bundle arguments = new Bundle();
        arguments.putInt(ARGUMENT_TEAM_ID, teamId);
        arguments.putInt(ARGUMENT_CREATOR_ID, creatorId);
        arguments.putString(ARGUMENT_TEAM_NAME, teamName);
        arguments.putString(ARGUMENT_COMPETITION_NAME, competitionName);
        JoinTeamApplyAbilityFragment fragment = new JoinTeamApplyAbilityFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    @Override
    public void setPresenter(@NonNull JoinTeamApplyContract.Presenter presenter) {
        this.presenter = checkNotNull(presenter);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_join_team_apply_ability,
                container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);

        Button finishBtn = (Button) view.findViewById(R.id.finish_btn);
        finishBtn.setOnClickListener(v -> {
            if (abilityEdit.getText().toString().trim().isEmpty()) {
                abilityEdit.setError("此项不能为空");
            } else {
                User user = JSON.parseObject(
                        AppController.getInstance().getCache().getAsString("user"), User.class);
                if (user.getSchool() == null || user.getSchool().isEmpty()) {
                    toUpdateUserInfo();
                } else if (user.getDegree() == null || user.getDegree().isEmpty()) {
                    toUpdateUserInfo();
                } else if (user.getRealName() == null || user.getRealName().isEmpty()) {
                    toUpdateUserInfo();
                } else {
                    sendApply(user);
                }
            }
        });
    }

    private void sendApply(User user) {
        Apply apply = new Apply();
        apply.setAbility(abilityEdit.getText().toString()
                .trim());
        apply.setApplyUserId(user.getId());
        apply.setTeamCreatorId(this.getArguments().getInt(ARGUMENT_CREATOR_ID));
        apply.setTeamId(this.getArguments().getInt(ARGUMENT_TEAM_ID));
        apply.setTeamName(this.getArguments().getString(ARGUMENT_TEAM_NAME));
        apply.setCompetitionName(this.getArguments().getString(ARGUMENT_COMPETITION_NAME));
        presenter.sendAbility(apply);
    }

    private void toUpdateUserInfo() {
        Intent toUpdateUser = new Intent(getActivity(), EditUserActivity.class);
        startActivity(toUpdateUser);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Integer result = data.getIntExtra("result", -1);
        if (result == -1) {
            Toast.makeText(getActivity(),
                    "为了您的安全，补充个人信息后才能申请", Toast.LENGTH_SHORT).show();
        } else if (result.equals(ResultTypeEnum.FAILED.getValue())) {
            Toast.makeText(getActivity(),
                    "补充个人信息后失败", Toast.LENGTH_SHORT).show();
        } else {
            User user = JSON.parseObject(
                    AppController.getInstance().getCache().getAsString("user"), User.class);
            sendApply(user);
        }
    }

    private void initViews(View view) {
        abilityEdit = (EditText) view.findViewById(R.id.ability_edit);
        loadingSmile = (LVCircularSmile) view.findViewById(R.id.lv_circularSmile);
    }

    @Override
    public void showLoading() {
        loadingSmile.setVisibility(View.VISIBLE);
        loadingSmile.startAnim();
    }

    @Override
    public void hideLoading() {
        loadingSmile.setVisibility(View.GONE);
        loadingSmile.stopAnim();
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void toSuccessActivity(String s) {
        Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra("RESULT", "OK");
        getActivity().setResult(ResultTypeEnum.SUCCESS.getValue(), intent);
        getActivity().finish();
    }
}
